Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

422
Visualizações
Why does mypy not accept a list[str] as a list[Optional[str]]?

Example 1:

from typing import List, Optional

def myfunc() -> List[Optional[str]]:
    some_list = [x for x in "abc"]
    return some_list

Mypy complains on example 1:

Incompatible return value type (got "List[str]", expected "List[Optional[str]]")

However, this example gets no complaint:

Example 2:

def myfunc() -> List[Optional[str]]:
    some_list = [x for x in "abc"]
    return list(some_list)

What is the explanation for the inconsistent behavior?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Since in Python lists are invariant (see the examples here and here).

If we pass List[str] to someone that expects List[Optional[str]], that someone may add a None to our list and break our assumptions. The second example is valid however as the output of list() in the return statement is not saved anywhere and no one can depend on the the returned value being mutated illegally .

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda